/**
 * @FileName: PublicProvider.java
 * @Package: dao.provider
 * @author youshipeng
 * @created 2016/11/9 16:53
 * <p>
 * Copyright 2016 ziroom
 */
package top.swimmer.boot.dao.provider;

import org.apache.ibatis.binding.MapperMethod;

import java.util.Map;

import static top.swimmer.boot.util.ModelUtils.degrade;

/**
 * <p></p>
 *
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author youshipeng
 * @since 1.0
 * @version 1.0
 */
public class PublicProvider {

    private static final String ID = "id";

    public String insert(Object entity) throws Exception {
        StringBuilder fieldsBuilder = new StringBuilder("");
        StringBuilder valuesBuilder = new StringBuilder("");
        try {
            Map<String, Object> params = degrade(entity);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                fieldsBuilder.append(entry.getKey()).append(", ");
                valuesBuilder.append("#{").append(entry.getKey()).append("}").append(", ");
            }
            return new StringBuilder("insert into ").append(entity.getClass().getSimpleName()).append("(")
                    .append(fieldsBuilder.substring(0, fieldsBuilder.length() - 2)).append(") values").append("(")
                    .append(valuesBuilder.substring(0, valuesBuilder.length() - 2)).append(");").toString();
        } catch (Exception e) {
            throw new Exception("insert provider error.", e);
        }
    }

    public String update(MapperMethod.ParamMap params) throws Exception {
        StringBuilder setBuilder = new StringBuilder("");
        try {
            Object entity = params.get("entity");
            Map<String, Object> fields = degrade(entity);
            for (Map.Entry<String, Object> entry : fields.entrySet()) {
                if (!ID.equals(entry.getKey())) {
                    setBuilder.append(entry.getKey()).append(" = ")
                            .append("#{entity.").append(entry.getKey()).append("}").append(", ");
                }
            }
            return new StringBuilder("update ").append(entity.getClass().getSimpleName())
                    .append(" set ").append(setBuilder.substring(0, setBuilder.length() - 2))
                    .append(" where id = #{id}").toString();
        } catch (Exception e) {
            throw new Exception("update provider error.", e);
        }
    }
}